﻿using System;
using System.Collections.Generic;

using System.Text;
using Common;
using System.IO;
using System.Windows.Forms;
using System.Reflection;

namespace ImageProcesser
{
    static class AppInstance
    {
        private static ImageProcessApp app;
        private static List<IProcessorPlugin> plugins;
        public static List<Assembly> PluginAsms;
        public static void Initialize()
        {
            plugins = new List<IProcessorPlugin>();
            PluginAsms = new List<Assembly>();
            app = new ImageProcessApp();
            foreach (string fileName in Directory.GetFiles(Directory.GetParent(Application.ExecutablePath) + ".\\Plugins"))
            {
                if (fileName.EndsWith(".dll", StringComparison.OrdinalIgnoreCase))
                {
                    try
                    {
                        Assembly asm = Assembly.LoadFile(fileName);
                        foreach (Type t in asm.GetTypes())
                        {
                            bool succ = t.FindInterfaces(new TypeFilter((Type t1, Object obj) => (t1.FullName == obj.ToString())), "Common.IProcessorPlugin").Length != 0;
                            if (succ)
                            {
                                IProcessorPlugin p = (IProcessorPlugin)(t.GetConstructor(System.Type.EmptyTypes).Invoke(null));
                                p.Load(app);
                                plugins.Add(p);
                                PluginAsms.Add(asm);
                            }
                        }
                    }
                    catch (Exception)
                    {
 
                    }
                }
            }
        }

        public static void UnInitialize()
        {
            foreach (IProcessorPlugin p in plugins)
                p.Unload();
        }

        public static ImageProcessApp GetApplication()
        {
            return app;
        }

        public static List<IProcessorPlugin> GetPlugins()
        {
            return plugins;
        }

    }
}
